package com.sea;

import com.sea.config.SerialPortManager;
import com.sea.view.MainView;
import de.felixroske.jfxsupport.AbstractJavaFxApplicationSupport;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.annotation.PreDestroy;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class SerialPortStudyApplication extends AbstractJavaFxApplicationSupport implements CommandLineRunner {

    private static Logger logger = LoggerFactory.getLogger(SerialPortStudyApplication.class);

    public static void main(String[] args) {
        launch(SerialPortStudyApplication.class, MainView.class, new CustomSplashScreen(), args);
    }

    @Override
    public void run(String... args) throws Exception {
        try {
            String port = System.getProperty("user.dir") + "\\port.json";
            String host_1_3 = System.getProperty("user.dir") + "\\host_1_3.json";
            String host_2_3 = System.getProperty("user.dir") + "\\host_2_3.json";
            String host_1_2 = System.getProperty("user.dir") + "\\host_1_2.json";
            String host_2_2 = System.getProperty("user.dir") + "\\host_2_2.json";
            delFile(port);
            delFile(host_1_3);
            delFile(host_2_3);
            delFile(host_1_2);
            delFile(host_2_2);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }

    private void delFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
            logger.info("删除" + filePath + "文件成功！");
        }
    }

    @PreDestroy
    public void destroy() {
        SerialPortManager.closeSerialPort();
    }

    @Override
    public void start(Stage stage) throws Exception {
        super.start(stage);
    }

    @Override
    public Collection<Image> loadDefaultIcons() {
        return Arrays.asList(new Image(this.getClass().getClassLoader().getResource("images/bluesea.gif").toExternalForm()));
    }
}
